package com.gnerv.cms.controller;

import com.gnerv.cms.common.Result;
import com.gnerv.cms.exception.BusinessException;
import com.google.common.io.Files;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * <p>
 * 基础平台-部署信息 前端控制器
 * </p>
 *
 * @author Gnerv LiGen
 * @since 2019-10-10
 */
@Slf4j
@Api(tags = "文件管理")
@CrossOrigin
@RestController
@RequestMapping(value = "/api/manage/file")
public class FileController {

    private static String FILE_PATH = "/Users/ligen/code/gitee";

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public Result uploadFiles(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BusinessException("上传文件不能为空！");
        }
        File fileObj = new File(FILE_PATH, file.getOriginalFilename());
        Files.write(file.getBytes(), fileObj);
        return Result.response().data("url", "http://localhost:8901/api/manage/file/download/" + file.getOriginalFilename());
    }

    @RequestMapping(value = "download/{fileName}", method = RequestMethod.GET)
    public Result downloadFile(@PathVariable(value = "fileName") String fileName,HttpServletResponse response) {
        try {
            //设置文件名和编码
            String name = URLEncoder.encode("demo.mp4", "UTF-8");
            response.setHeader("Content-Disposition", "inline;filename=" + name);
            FileCopyUtils.copy(new FileInputStream(new File(FILE_PATH, fileName)), response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.response();
    }

}
